from django import forms
from django.forms import ModelForm
from django.utils.safestring import mark_safe
from django.template import Context, Template
from django.template.loader import get_template


from pypsqueak.page.models import Page
from pypsqueak.page.widgets import *
from pypsqueak.chrome.widgets import *
from pypsqueak.chrome.forms import *
from pypsqueak.group.models import Assignment
from pypsqueak.group.widgets import GroupAssignmentChoiceWidget
from pypsqueak.artifact.forms import ArtifactInsertForm
from pypsqueak.artifact.widgets import *

class PageDeleteForm(ChromeModelForm):
	""" Used for deleting pages """
	pass

class PageInsertForm(ChromeModelForm):
	""" Form for creating new pages. Provides a choice of assignments for initialization. """
	assignment = forms.ModelChoiceField (
		queryset=Assignment.objects.all(),
		widget=GroupAssignmentChoiceWidget(),
		required=False,
		label="Choose a template to build your new page" )

	class Meta:
		model = Page
		exclude = ( 'title','body','parent','order','artifacts' )


class PageUpdateForm(ChromeModelForm):
	""" Form for editing pages """
	title = forms.CharField( widget=forms.TextInput(attrs={'size':'50'} ))
	body = forms.CharField( widget=PageBodyWidget )
	parent = ParentChoiceField( queryset=Page.objects.none(),
								required=False,
								label="Page Location" )

	def __init__(self, *args, **kwargs):
		super(PageUpdateForm, self).__init__(*args,**kwargs)
		self.fields['parent'].LoadPage(self.instance)
		self.fields['body'].widget.set_user(self.instance.user)

	class Media:
		#css = {'all': ('http://yui.yahooapis.com/2.7.0/build/fonts/fonts-min.css',)	}
		js = ( "/files/lib/jquery/js/jquery-1.3.2.min.js",
				"/files/lib/jquery/js/ui.core.js",
				"/files/lib/jquery/js/ui.tabs.js",	)

	class Meta:
		model = Page
		fields = ('title','order','body','parent')



class PageArtifactAjaxInsertForm(ArtifactInsertForm):
	"""
	Form using AJAX to insert assignments.
	Mimicks an ArtifactInsertForm, but adds ajax & a post url
		of {page.get_absolute_url}/artifact/insert/?xhr=true
	Owning page is set via set_master
	"""
	file = forms.FileField(widget=AjaxFileUploadWidget)

	def set_master(self, page):
		""" Save the page value for rendering template """
		self.page = page
		self.fields['file'].widget.set_url(PageArtifact.get_insert_url(self.page))
		self.fields['file'].widget.set_ajax_target('PageArtifactList')


class PageArtifactInlineUpdateForm(ChromeModelForm):
	"""
	Form used for in-line editing of a list of Artifacts
	"""

	# Use __init__ and save() to update the artifact title with this field.
	artifact_title = forms.CharField(
				widget=forms.TextInput(attrs={'size':'50'}),
				min_length=1, max_length=150,
				label="Title" )
	order = forms.IntegerField(
				widget=forms.HiddenInput(),
				initial=0,
				label="Order" )
	delete_me = forms.BooleanField(
				#widget=AjaxDeleteMeWidget(),
				required=False,
				label="Delete on save?" )

	def __init__(self, *args, **kwargs):
		super(PageArtifactInlineUpdateForm, self).__init__(*args,**kwargs)
		# Set artifact title field.
		if 'instance' in kwargs:
			self.fields['artifact_title'].initial = self.instance.artifact.title

	def save(self, Commit=True):
		artifact = self.instance.artifact
		pa = super(PageArtifactInlineUpdateForm, self).save(Commit)

		# If delete_me is on, then page artifact will be None and we don't update the artifact.
		if not pa == None:
			pa.artifact.title = self.cleaned_data['artifact_title']
			pa.artifact.save()
		else:
			# pa deleted.  Look to see if artifact is used elsewhere. If not, delete
			if len(PageArtifact.objects.filter(artifact=artifact)) == 0:
				artifact.delete()

		return pa

	def as_template(self):
		return render_to_string(
			'page/PageArtifactInlineUpdateForm.html',
			{'form': self })


	# Note that to make this form sortable, you have to include the init js.
	# 	See page_update.html template for an example.
	class Media:
		css = {'all': ('/files/lib/jquery/css/base/ui.all.css',)}
		js = ('/files/lib/jquery/js/jquery-1.3.2.min.js',
				'/files/lib/jquery/js/ui.core.js',
				'/files/lib/jquery/js/ui.sortable.js',
				'/files/js/Page/PageArtifactInlineUpdateForm.js')


	class Meta:
		model = PageArtifact
		exclude = ( 'page','artifact' )

